using System;
using System.Web;
using System.Web.Util;
using Microsoft.IdentityModel.Protocols.WSFederation;

namespace LogOnWithACSLibrary
{
    /// <summary>
    /// A custom request validator which enables claims to pass through ASP.NET request validation when working with WIndows Identity Foundation.
    /// Problem: It became a well known issue with the Windows Identity Foundation in ASP.NET 4.0 because when you do a federated sign on, 
    /// WIF receives the token as a chunk of XML. The validator doesn't approve because of the angle brackets. 
    /// Solution: 
    /// 1.Disable validation in the page declaration within WebForms, or stick a [ValidateInput(false)] attribute on an MVC controller.
    /// 2.Set the validation mode to 2.0, use ClaimsRequestValidator in web.config as below:
    /// <httpRuntime requestValidationMode="2.0" requestValidationType="LogOnWithACSLibrary.ClaimsRequestValidator" />
    /// </summary>
    public class ClaimsRequestValidator : RequestValidator
    {
        protected override bool IsValidRequestString(HttpContext context, string value,
                                                     RequestValidationSource requestValidationSource,
                                                     string collectionKey, out int validationFailureIndex)
        {
            validationFailureIndex = 0;

            if (requestValidationSource == RequestValidationSource.Form &&
                collectionKey.Equals(WSFederationConstants.Parameters.Result, StringComparison.Ordinal))
            {
                SignInResponseMessage message =
                    WSFederationMessage.CreateFromFormPost(context.Request) as SignInResponseMessage;
                /// OK, it is a federated sign on.
                if (message != null)
                {
                    return true;
                }
            }
            return base.IsValidRequestString(context, value, requestValidationSource, collectionKey,
                                             out validationFailureIndex);
        }
    }
}